package fm.dongman.modellib.source;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.util.Log;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import fm.dongman.animefm.contractlib.IModel;
import fm.dongman.animefm.contractlib.contract.UserEditContract;
import fm.dongman.modellib.PostFileHelper;
import fm.dongman.modellib.RemoteHelper;
import fm.dongman.modellib.StaticArea.StaticUrl;
import fm.dongman.modellib.local.LoginLocalDataSource;
import fm.dongman.modellib.model.UserModel;
import fm.dongman.modellib.remote.RemoteOperationHelper;
import fm.dongman.modellib.remote.UserEditRemoteDataSource;

/**
 * 用户资料更改
 * Created by KUIGE on 2017/11/26.
 */

public class UserEditRepository implements UserEditContract.IUserEditDataSource {
    private static UserEditRepository SINGLETON;
    private LoginLocalDataSource mLocal; // 获取用户信息
    private UserEditRemoteDataSource mRemote;
    private Context mContext;

    public static UserEditRepository getInstance(Context context) {
        if (SINGLETON == null) {
            SINGLETON = new UserEditRepository(context);
        }
        return SINGLETON;
    }

    private UserEditRepository(Context context) {
        mContext = context;
        mLocal = LoginLocalDataSource.getInstance(context);
        mRemote = UserEditRemoteDataSource.getInstance();
    }

    @Override
    public void submitUserInfo(@NotNull IModel.IUserModel userInfo, @NotNull LoadSourceCallback<? super String> callback) {
        mRemote.submitUserInfo(userInfo, callback);
    }

    @Override
    public void submitUserPicture(@NotNull Bitmap picture, @NotNull LoadSourceCallback<? super String> callback) {
        JSONObject jsonObject = PostFileHelper.getInstance().uploadMultiFile("http://api.dongman.fm/picture/uploadAvatar", picture, mContext.getCacheDir().getPath(), StaticUrl.TOKEN_KEY);
        if (jsonObject == null) {
            callback.onDataLoadFiled();
            return;
        }
        try {
            callback.onDataLoaded(jsonObject.getJSONObject("data").getString("image_url"));
        } catch (JSONException e) {
            callback.onDataLoadFiled();
            e.printStackTrace();
        }
    }

    @Override
    public void getData(@NotNull LoadSourceCallback<? super IModel.IUserModel> callback) {
        mRemote.getData(callback);
    }

    @Override
    public void saveData(IModel.IUserModel dataModel) {
        mLocal.saveData(dataModel);
    }

    @Override
    public void refreshData() {
    }

    @Override
    public void offLine() {
    }
}
